#!/bin/sh

uniqify()
{
    local p=
    local paths_list=
    for p in $MODULES_ORDERED; do
        case "$paths_list" in
        *"$p"*) ;;
        *) paths_list="$paths_list,$p";;
        esac
    done
    #trim spurious coma
    MODULES_ORDERED="${paths_list#,*}"
}

modules_ordered_build()
{
    local deps=
    local m=
    for m; do
        if modinfo $kmod_option_basedir -k $kernel_release $m >/dev/null 2>&1;then 
            echo "module $m found, adding..."
        else
            echo "module $m not found, skipping..."
            continue
        fi
        deps=$(modinfo $kmod_option_basedir -k $kernel_release \
                                                             --field depends $m)
        if test -n "$deps"; then
            modules_ordered_build $deps
        fi
        MODULES_ORDERED="$MODULES_ORDERED,$(modinfo $kmod_option_basedir \
                                        -k $kernel_release --field filename $m)"
    done
    #trim spurious coma
    MODULES_ORDERED="${MODULES_ORDERED#,*}"
}

#recursive emiting of cpio dir entries for the module
dirs_emit()
{
    local cur=$(dirname $1)
    if test "$cur" = "/lib/modules/$kernel_release"; then
        return;
    fi

    for p in $DIRS_EMITED; do
        if test "$p" = "$cur"; then
            return;
        fi
    done
    dirs_emit $cur
    echo "dir $cur 0755 0 0" >>$cpio
    DIRS_EMITED=$DIRS_EMITED,$cur
}

cpio_kmod_files='modules.alias.bin,modules.builtin.bin,modules.dep.bin'

cpio_emit()
{
    local f=
    local m=
    for f in $cpio_kmod_files; do
        echo "file /lib/modules/$kernel_release/$f \
$kernel_modules_base_dir/lib/modules/$kernel_release/$f \
0644 0 0" >>$cpio
    done

    for m in $MODULES_ORDERED; do
        dirs_emit $m
        echo "file $m $kernel_modules_base_dir$m 0644 0 0" >>$cpio
    done
}

################################################################################

kernel_modules_base_dir=$1
kernel_release=$2
modules=$3
cpio=$4
MODULES_ORDERED=
DIRS_EMITED=/lib/modules/$kernel_release

if test "$kernel_modules_base_dir" = '/'; then
    kmod_option_basedir=
    kernel_modules_base_dir=
else
    kmod_option_basedir="--basedir=$kernel_modules_base_dir"
fi

IFS=,
modules_ordered_build $3
uniqify
cpio_emit
